package com.abc.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.xxx.dao.ViewMapper;
import com.abc.xxx.model.View;
import com.abc.xxx.service.ViewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ViewServiceImpl extends ServiceImpl<ViewMapper, View> implements ViewService {


    @Transactional
    @Override
    public void updatePagePermissions(List<View> pages) {
        baseMapper.deleteByType(View.PAGE);
        pages.forEach(p -> p.setType(View.PAGE));
        saveBatch(pages);
    }

    @Override
    public List<View> findButtonsByPageCode(String pageCode) {
        return baseMapper.findByParentAndType(pageCode, View.BUTTON);
    }

    @Override
    public List<String> findAllPagesCodes() {
        QueryWrapper<View> w = new QueryWrapper<>();
        w.select("code");
        w.eq("type", View.PAGE);
        return list(w).stream().map(View::getCode).collect(Collectors.toList());
    }

    @Override
    public List<View> findAllButtons() {
        QueryWrapper<View> w = new QueryWrapper<>();
        w.eq("type", View.BUTTON);
        return list(w);
    }

    @Override
    public List<View> findPageMetadata() {
        QueryWrapper<View> w = new QueryWrapper<>();
        w.orderByAsc("`order`");
        List<View> list = list(w);
        List<View> result = convertToPageListWithButtons(list);
        return result;
    }

    @Override
    public void deletePageMetadata(String pageCode) {
        QueryWrapper<View> w = new QueryWrapper<>();
        w.eq("`code`",pageCode);
        w.or();
        w.eq("`parent`",pageCode);
        remove(w);
    }

    @Override
    public boolean isViewCodeExists(String code) {
        QueryWrapper<View> w = new QueryWrapper<>();
        w.eq("`code`",code);
        return retBool(count(w));
    }

    /**
     * 转换成page-button一对多的结构
     * @param views
     * @return
     */
    public List<View> convertToPageListWithButtons(final List<View> views) {
        log.info("数据结构转换: 页面、按钮权限List --> Tree");
        return views.stream()
                .filter(p1 -> p1.isPage())
                .map(page -> {
                    String pageCode = page.getCode();
                    List<View> buttons = views.stream()
                            .filter(p2 -> p2.isButton() && p2.isChildOf(pageCode))
                            .collect(Collectors.toList());
                    page.getChildren().addAll(buttons);
                    return page;
                })
                .collect(Collectors.toList());
    }

}
